<?php

namespace App\Service\OpenShop\Feishu;

use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteMissionEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Library\Rms\RmsShopApi;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopEmployeeNotice;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPayHistoryModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSiteMissionModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserIdentityCardModel;
use App\Models\OpenShop\ShopCheckAccept\OpenShopCheckAcceptModel;
use App\Models\OpenShop\ShopEngineeringConstruction\OpenShopEngineeringConstructionModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Service\OpenShop\User\RmsUserService;
use App\Service\Rms\ShopService;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Log;

class NoticeService
{
    public string $orderNo; // 订单号
    public object $orderInfo; // 订单详情

    /**
     * 订单跳转地址
     *
     * @var string
     */
    public string $url; //

    /**
     * 任务触发人信息
     *
     * @var array
     */
    public array $handleUserInfo = [];

    /**
     * 推送人 ID
     *
     * @var array
     */
    public array $pushUserInfo = [];

    /**
     * 任务消息中的 处理人消息
     *
     * @var array
     */
    public array $missionDealUserInfo = [];


    public array  $historyUserList     = [];
    public string $historyDealUserName = '';
    public string $historyDealUserType = '员工'; // 员工,商家

    public object $siteMissionInfo; // 最新的 site mission info`
    public object $siteMissionInfoDeal; // 已处理的 site Mission info

    public string $noticeContent  = '';
    public string $missionType    = '审核'; // 审核....
    public string $missionContent = '';

    /**
     * @param string $orderNo 订单编号
     * @param int $handleUserId 消息触发者的 userId
     */
    public function __construct(string $orderNo, int $handleUserId = 0)
    {
        $this->orderNo   = $orderNo;
        $this->url       = BaseService::getOrderInfoWenAppUrl($this->orderNo, 0);
        $this->orderInfo = $this->getOrderInfo();

        if ($handleUserId > 0) {
            $this->setHandleUserInfo($handleUserId);
        }

    }

    /**
     * 根据 userId 获取用户详情
     *
     * @param string $userId
     * @return mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getUserInfoById(string $userId)
    {
        $body = RmsUserService::getRmsUserInfoByUserIds([$userId]);
        return $body['data'][0] ?? '';
    }

    /**
     * set 处理人信息 - 消息推送触发者
     *
     * @param int $userId
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function setHandleUserInfo(int $userId)
    {
        if (0 == $userId) {
            return;
        }
        Log::info("userInfo-userId", ['userId' => $userId]);
        $result = RmsUserService::getRmsUserInfoByUserIds([$userId]);
        Log::info("userInfo", ['userInfo' => $result]);
        $this->handleUserInfo = $result['data'][0];
    }

    /**
     * set 历史处理人
     *
     * @param array $userIds
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function setHistoryUserList(array $userIds)
    {
        if (empty($userIds)) {
            return;
        }
        $body                  = RmsUserService::getRmsUserInfoByUserIds($userIds);
        $data                  = $body['data'];
        $this->historyUserList = (array)$data;
    }

    /**
     * set 消息通知标题
     *
     * @param string $noticeContent
     */
    public function setNoticeContent(string $noticeContent)
    {
        $this->noticeContent = $noticeContent;
    }

    /**
     * 获取任务详情
     *
     * @param false $isHandle 是否已经处理
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getLastSiteMissionInfo($isHandle = false)
    {
        return OpenShopSiteMissionModel::query()
                                       ->where("orderNo", $this->orderNo)
                                       ->when($isHandle, function ($q) {
                                           $q->where('status', SiteMissionEnum::STATUS_2);
                                       })
                                       ->orderBy('id', 'DESC')
                                       ->first();
    }

    public function setHistoryDealByUserId(int $userId)
    {
        $userInfo                  = $this->getUserInfoById($userId);
        $this->historyDealUserName = $userInfo['username'] ?? '';
    }

    public function setHistoryDealUserName(string $userName)
    {
        $this->historyDealUserName = $userName;
    }

    /**
     * set 任务类型 审核..
     *
     * @param string $missionType
     */
    public function setMissionType(string $missionType)
    {
        $this->missionType = $missionType;
    }

    public function setHistoryUserType(string $type)
    {
        $this->historyDealUserType = $type;
    }

    /**
     * 设计师模块数据推送
     */
    public function spaceDesignJobV2(string $missionContent)
    {
        $siteInfo = $this->getLastSiteMissionInfo();
        $this->setOpenBoardUrl($siteInfo->id);
        if (!empty($siteInfo)) {
            $noticeUid     = $siteInfo['dealUid'];
            $designUidInfo = $this->getUserInfoById($noticeUid);

            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = $this->noticeContent;
            $notice->orderId      = $this->orderInfo->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$this->orderInfo->shopCode;
            $notice->shopName     = $this->getShopName();
            $notice->operatorName = $this->handleUserInfo['username'];
            $notice->createdAt    = time();
            $notice->updatedAt    = time();

            $notice->save();

            if (strlen($designUidInfo['feishuUserId'])) {
                MessageService::spaceDesignJob(
                    $designUidInfo['feishuUserId'],
                    $this->orderNo,
                    $this->orderInfo->shopCode,
                    $designUidInfo['username'],
                    $this->url,
                    $this->getShopName(),
                    $siteInfo->createdAt->toDateString(),
                    date("Y-m-d H:i:s", $siteInfo->expiredAt),
                    $this->missionType,
                    $missionContent
                );
            }
        }
    }

    /**
     * 设计师模块数据推送
     */
    public function spaceDesignJob()
    {
        $siteInfo = $this->getLastSiteMissionInfo();

        if (!empty($siteInfo)) {

            $this->setOpenBoardUrl($siteInfo->id);

            $noticeUid     = $siteInfo['dealUid'];
            $designUidInfo = $this->getUserInfoById($noticeUid);

            // 防止重复推送消息
            $notice = OpenShopEmployeeNotice::query()
                                            ->where('orderId', $this->orderInfo->id)
                                            ->where('userId', $noticeUid)
                                            ->where('content', $this->noticeContent)
                                            ->first();
            if (!empty($notice)) {
                return;
            }

            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = $this->noticeContent;
            $notice->orderId      = $this->orderInfo->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$this->orderInfo->shopCode;
            $notice->shopName     = $this->getShopName();
            $notice->operatorName = $this->handleUserInfo['username'] ?? '';
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();

            if (isset($designUidInfo['feishuUserId']) && strlen($designUidInfo['feishuUserId'])) {
                MessageService::spaceDesignJob(
                    $designUidInfo['feishuUserId'],
                    $this->orderNo,
                    $this->orderInfo->shopCode,
                    $designUidInfo['username'],
                    $this->url,
                    $this->getShopName(),
                    $siteInfo->createdAt->toDateString(),
                    date("Y-m-d H:i:s", $siteInfo->expiredAt),
                    $this->missionType,
                    $this->missionContent
                );
            }
        }
    }

    /**
     * 设计模块历史推送
     *
     * @param string $historyText
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function spaceDesignHistory(string $historyText = '', string $field = 'designName', int $stepStatus = 0)
    {
        if (!count($this->historyUserList)) {
            return;
        }

        if (in_array($stepStatus, MissionTemplateEnum::OPEN_MISSION_LISTS)) {
            $siteId = OpenShopSiteMissionModel::getLastFinishSiteId($this->orderNo, $stepStatus);
            $this->setOpenBoardUrl($siteId);
        } else {
            $this->setUrl();
        }

        $shopName = $this->getShopName();

        foreach ($this->historyUserList as $user) {
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = $this->noticeContent;
            $notice->orderId      = $this->orderInfo->id;
            $notice->userId       = $user['id'];
            $notice->shopCode     = (string)$this->orderInfo->shopCode;
            $notice->shopName     = $shopName;
            $notice->operatorName = $this->handleUserInfo['username'];
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();
        }

        $feishuList = array_values(array_unique(array_filter(array_column($this->historyUserList, 'feishuUserId'))));

        $preparationName = empty($this->historyDealUserName) ? $this->orderInfo->spaceDesignRel->$field : $this->historyDealUserName;

        MessageService::spaceDesignJobHistory(
            $feishuList,
            $this->orderNo,
            $this->orderInfo->shopCode,
            $preparationName,
            $this->orderInfo->spaceDesignRel->updatedAt->toDateString(),
            $this->url,
            $historyText,
            $this->historyDealUserType
        );
    }

    /**
     * 开业报告模块数据推送
     */
    public function startBusinessJob()
    {
        $siteInfo = $this->getLastSiteMissionInfo();
        $this->setOpenBoardUrl($siteInfo->id);
        if (!empty($siteInfo)) {
            $noticeUid     = $siteInfo['dealUid'];
            $designUidInfo = $this->getUserInfoById($noticeUid);

            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = $this->noticeContent;
            $notice->orderId      = $this->orderInfo->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$this->orderInfo->shopCode;
            $notice->shopName     = $this->getShopName();
            $notice->operatorName = $this->handleUserInfo['username'];
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();

            if (strlen($designUidInfo['feishuUserId'])) {
                MessageService::spaceDesignJob(
                    $designUidInfo['feishuUserId'],
                    $this->orderNo,
                    $this->orderInfo->shopCode,
                    $designUidInfo['username'],
                    $this->url,
                    $this->getShopName(),
                    $siteInfo->createdAt->toDateString(),
                    date("Y-m-d H:i:s", $siteInfo->expiredAt),
                    $this->missionType,
                    $this->missionContent
                );
            }
        }
    }

    /**
     * 开业报告模块数据推送历史数据
     */
    public function startBusinessHistory(string $historyText = '')
    {
        if (!count($this->historyUserList)) {
            return;
        }

        $shopName = $this->getShopName();

        // 有帮扶的跳转帮扶
        $cruiseOrderModel = CruiseOrderModel::getOrder(0, CruiseOrderModel::TYPE_NEW_SHOP_HELP, $this->orderNo, false);
        if ($cruiseOrderModel) {
            $this->url = BaseService::getCruiseTaskDetailUrl($cruiseOrderModel->id);
        } else {
            $siteId = OpenShopSiteMissionModel::getLastFinishSiteId($this->orderNo, MissionTemplateEnum::STEP_STATUS_18);
            $this->setOpenBoardUrl($siteId);
        }

        foreach ($this->historyUserList as $user) {
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = $this->noticeContent;
            $notice->orderId      = $this->orderInfo->id;
            $notice->userId       = $user['id'];
            $notice->shopCode     = (string)$this->orderInfo->shopCode;
            $notice->shopName     = $shopName;
            $notice->operatorName = $this->handleUserInfo['username'];
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();
        }

        $feishuList = array_filter(array_column($this->historyUserList, 'feishuUserId'));
        $userInfo   = $this->getUserInfoById($this->orderInfo->startBusinessRel->createdByUid);

        MessageService::spaceDesignJobHistory(
            $feishuList,
            $this->orderNo,
            $this->orderInfo->shopCode,
            $userInfo['username'],
            $this->orderInfo->startBusinessRel->createdAt->toDateString(),
            $this->url,
            $historyText,
            '员工'
        );
    }

    /**
     * 选址待审核
     */
    public function siteLocationAuditJob($text = '处理')
    {
        $messageService = new MessageService();
        $this->setSiteUrl();

        $userList = self::getPushUserFeiShuId();
        $userList = array_filter($userList);

        if (!empty($userList)) {
            $messageService->sendCommonJob(
                [
                    'orderNo'          => $this->getOrderNo(),
                    //'missionType'      => $this->getMissionType(),
                    'missionName'      => $this->getMissionContent(),
                    'shopCode'         => $this->getShopCode(),
                    'shopName'         => $this->getShopName(),
                    //'dealUsername'     => $this->getMissionDealUserInfo()['username'],
                    'missionTimeStart' => date('Y-m-d H:i:s', time())
                ], $userList, $this->getUrl(), '**您有一条选址待' . $text . '!**'
            );
        }

        self::saveNotice($this->getMissionContent());
    }

    /**
     * 选址待审核  选址负责人审核
     */
    public function siteLocationAuditJobWithResponsible($approval)
    {
        $messageService = new MessageService();
        $this->setSiteUrl();

        $userList = self::getPushUserFeiShuId();
        $userList = array_filter($userList);

        if (!empty($userList)) {
            $messageService->sendCommonJob(
                [
                    'orderNo'          => $this->getOrderNo(),
                    'missionType'      => $this->getMissionType(),
                    'missionName'      => $this->getMissionContent(),
                    'shopCode'         => $this->getShopCode(),
                    'shopName'         => $this->getShopName(),
                    'approval'         => $approval,
                    //'dealUsername'     => $this->getMissionDealUserInfo()['username'],
                    'missionTimeStart' => date('Y-m-d H:i:s', time())
                ], $userList, $this->getUrl(), '**您有一条选址任务待处理!**'
            );
        }

        self::saveNotice($this->getMissionContent());
    }

    /**
     * 门店合同待核实
     */
    public function shopContractCheckAudit($approval)
    {
        $messageService = new MessageService();
        $this->setSiteUrl();

        $userList = self::getPushUserFeiShuId();
        $userList = array_filter($userList);

        if (!empty($userList)) {
            $messageService->sendCommonJob(
                [
                    'orderNo'          => $this->getOrderNo(),
                    'missionType'      => $this->getMissionType(),
                    'missionName'      => $this->getMissionContent(),
                    'shopCode'         => $this->getShopCode(),
                    'shopName'         => $this->getShopName(),
                    'approval'         => $approval,
                    'missionTimeStart' => date('Y-m-d H:i:s', time())
                ], $userList, $this->getUrl(), '**您有一条合同待审批!**'
            );
        }

        self::saveNotice($this->getMissionContent());
    }

    /**
     * 选址待审核
     */
    public function siteLocationAuditJobByCharge()
    {
        $messageService = new MessageService();
        $this->setSiteUrl();

        $userList = self::getPushUserFeiShuId();
        $userList = array_filter($userList);

        if (!empty($userList)) {
            $messageService->sendCommonJob(
                [
                    'orderNo'          => $this->getOrderNo(),
                    'missionType'      => '审核',
                    'missionName'      => '选址表单待审核',
                    'shopCode'         => $this->getShopCode(),
                    'shopName'         => $this->getShopName(),
                    //'dealUsername'     => $this->getMissionDealUserInfo()['username'],
                    'missionTimeStart' => date('Y-m-d H:i:s', time())
                ], $userList, $this->getUrl(), '**您有一条选址任务待处理!**'
            );
        }

        self::saveNotice($this->getMissionContent());
    }


    public function siteLocationAuditHistory()
    {
        $messageService = new MessageService();
        $this->setSiteUrl();

        $sendMessage = [
            'orderNo'         => $this->getOrderNo(),
            'shopCode'        => $this->getShopCode(),
            'dealUserRole'    => '省区负责人',
            //'dealUsername'    => $this->getMissionDealUserInfo()['username'],
            'missionTimeDeal' => date('Y-m-d H:i:s', time())
        ];

        $messageService->sendCommonJob(
            $sendMessage, self::getPushUserFeiShuId(), $this->getUrl(), '**省区负责人通过选址表单审批**'
        );

        self::saveNotice($this->getMissionContent());
    }

    public function siteLocationAuditHistoryByCharge()
    {
        $messageService = new MessageService();
        $this->setSiteUrl();

        $sendMessage = [
            'orderNo'         => $this->getOrderNo(),
            'shopCode'        => $this->getShopCode(),
            'dealUserRole'    => '总部负责人',
            //'dealUsername'    => $this->getMissionDealUserInfo()['username'],
            'missionTimeDeal' => date('Y-m-d H:i:s', time())
        ];

        $messageService->sendCommonJob(
            $sendMessage, self::getPushUserFeiShuId(), $this->getUrl(), '**选址负责人通过选址表单审批**'
        );

        self::saveNotice($this->getMissionContent());
    }

    public function saveNotice($content)
    {
        foreach ($this->getPushUserInfo() as $pushUserInfo) {
            // 写入通知历史
            $userId = $pushUserInfo['id'];
            // 单独拆出来
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = $content;
            $notice->orderId      = $this->orderInfo->id;
            $notice->userId       = $userId;
            $notice->shopCode     = (string)$this->orderInfo->shopCode;
            $notice->shopName     = $this->getShopName();
            //$notice->operatorName = $this->getMissionDealUserInfo()['username'];
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();
        }
    }


    /*** ↓ 老接口推送数据 ↓ ***/


    /**
     * 支付成功后推通知
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param Collection $payHistory
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function paid(array $noticeUids, OpenShopSignOrderModel $order, Collection $payHistory)
    {
        if (!count($noticeUids)) {
            return;
        }
        $userIdentityCard = OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo);
        if (null === $userIdentityCard) {
            return;
        }
        $money      = $payHistory->map(function (OpenShopSignOrderPayHistoryModel $history) {
            if (0 == $history->isDeleted && 1 == $history->payStatus) {
                return $history->payPrice;
            }
            return 0;
        })->sum();
        $serialNums = $payHistory->map(function (OpenShopSignOrderPayHistoryModel $history) {
            if (0 == $history->isDeleted && 1 == $history->payStatus) {
                return $history->payNo;
            }
            return null;
        })->filter()->implode(',');

        $body = RmsUserService::getRmsUserInfoByUserIds($noticeUids);
        $url  = BaseService::getOrderInfoWenAppUrl($order->orderNo, 0);

        $merchantName = (string)$userIdentityCard->name;

        foreach ($noticeUids as $noticeUid) {
            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = "商家已完成合同支付";
            $notice->orderId      = $order->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$order->shopCode;
            $notice->shopName     = $merchantName . '的店';
            $notice->operatorName = $merchantName;
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();

            $feishuUserId = '';
            foreach (($body['data'] ?? []) as $item) {
                if ($item['id'] == $noticeUid) {
                    $feishuUserId = $item['feishuUserId'];
                }
            }
            if (strlen($feishuUserId)) {
                MessageService::paySuccessNotice($feishuUserId, $order->orderNo, $userIdentityCard->name,
                    $money / 100, date('Y-m-d H:i:s'), $serialNums, $url);
            }

        }
    }

    /**
     * 签约后推通知
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function signed(array $noticeUids, OpenShopSignOrderModel $order)
    {
        if (!count($noticeUids)) {
            return;
        }
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;
        $body         = RmsUserService::getRmsUserInfoByUserIds($noticeUids);

        foreach ($noticeUids as $noticeUid) {
            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = "商家已完成合同签约";
            $notice->orderId      = $order->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$order->shopCode;
            $notice->shopName     = $merchantName . '的店';
            $notice->operatorName = $merchantName;
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();

            $feishuUserId = '';
            foreach (($body['data'] ?? []) as $item) {
                if ($item['id'] == $noticeUid) {
                    $feishuUserId = $item['feishuUserId'];
                }
            }
            if (strlen($feishuUserId)) {
                $shopCode     = $order->shopCode;
                $contractNo   = 'KF' . $order->shopCode;
                $url          = BaseService::getOrderInfoWenAppUrl($order->orderNo, 0);
                $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;
                MessageService::completeAllContractsNotice(
                    $feishuUserId,
                    $order->orderNo,
                    $contractNo,
                    $shopCode,
                    $merchantName,
                    $url
                );
            }

        }
    }

    /**
     * 指派开发经理历史参与人 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function assignManagerHistory(array $noticeUids, OpenShopSignOrderModel $order, string $operatorName)
    {
        if (!count($noticeUids)) {
            return;
        }
        $body         = RmsUserService::getRmsUserInfoByUserIds($noticeUids);
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        $siteId = OpenShopSiteMissionModel::getLastFinishSiteId($order->orderNo, MissionTemplateEnum::STEP_STATUS_3);
        $url    = BaseService::getOpenBoardUrl($siteId);

        $managerInfo = OpenShopLocationModel::query()
                                            ->where("orderNo", $order->orderNo)
                                            ->where('step', MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER)
                                            ->first();
        if (!empty($managerInfo)) {
            foreach ($noticeUids as $noticeUid) {
                // 插入通知
                $notice               = new OpenShopEmployeeNotice;
                $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
                $notice->orderId      = $order->id;
                $notice->userId       = $noticeUid;
                $notice->shopCode     = (string)$order->shopCode;
                $notice->shopName     = $merchantName . '的店';
                $notice->operatorName = $operatorName;
                $notice->createdAt    = time();
                $notice->updatedAt    = time();
                $notice->save();
                $feishuUserId = '';
                foreach (($body['data'] ?? []) as $item) {
                    if ($item['id'] == $noticeUid) {
                        $feishuUserId = $item['feishuUserId'];
                    }
                }
                if (strlen($feishuUserId)) {
                    $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;
                    MessageService::assignManagerHistory(
                        $feishuUserId,
                        $order->orderNo,
                        $order->shopCode,
                        $operatorName,
                        $managerInfo->updatedAt->toDateString(),
                        $url
                    );
                }
            }
        }


    }

    /**
     * 合同签署失败
     * @param string $orderNo
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function contractError(
        string $orderNo,
        string $title = '合同签约'
    ) {
        $order = OpenShopSignOrderModel::query()
                                       ->where('orderNo', $orderNo)
                                       ->first();
        if (null === $order) {
            return;
        }
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($orderNo))->name;
        // 插入通知
        $notice               = new OpenShopEmployeeNotice;
        $notice->content      = "订单{$title}失败";
        $notice->orderId      = $order->id;
        $notice->userId       = $order->investmentManagerId;
        $notice->shopCode     = (string)$order->shopCode;
        $notice->shopName     = $merchantName . '的店';
        $notice->operatorName = '契约锁';
        $notice->createdAt    = time();
        $notice->updatedAt    = time();
        $notice->save();

        $body         = RmsUserService::getRmsUserInfoByUserIds([$order->investmentManagerId]);
        $feishuUserId = $body['data'][0]['feishuUserId'];
        if ($feishuUserId) {
            $url = BaseService::getOrderInfoWenAppUrl($order->orderNo, 0);
            MessageService::contractError(
                $feishuUserId,
                $order->orderNo,
                $order->shopCode,
                'KF' . $order->shopCode,
                $merchantName,
                $url
            );

        }

    }

    public static function preparationConfirmation2(
        array $noticeUids,
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        if (!count($noticeUids)) {
            return;
        }
        $body         = RmsUserService::getRmsUserInfoByUserIds($noticeUids);
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        $url       = BaseService::getOrderInfoWenAppUrl($order->orderNo, 0) ?? '';
        $spaceInfo = OpenShopSpaceDesignModel::query()
                                             ->where("orderNo", $order->orderNo)
                                             ->where('step', MainProcessEnum::SPACE_DESIGN_STEP_TYPE_CONFIRM_SHOP_INFO)
                                             ->first();

        foreach ($noticeUids as $noticeUid) {
            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
            $notice->orderId      = $order->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$order->shopCode;
            $notice->shopName     = $merchantName . '的店';
            $notice->operatorName = $operatorName;
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();

            $feishuUserId = '';
            foreach (($body['data'] ?? []) as $item) {
                if ($item['id'] == $noticeUid) {
                    $feishuUserId = $item['feishuUserId'];
                }
            }
            if (strlen($feishuUserId)) {
                $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

                MessageService::preparationConfirmation(
                    [$feishuUserId],
                    $order->orderNo,
                    $order->shopCode,
                    $spaceInfo["preparationName"],
                    $spaceInfo->updatedAt->toDateString(),
                    $url,
                    '',
                    '员工'
                );
            }
        }

    }

    /**
     * 指派空间设计师 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function assignSpaceDesign(
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        $spaceInfo = OpenShopSpaceDesignModel::query()
                                             ->where("orderNo", $order->orderNo)
                                             ->where('step',
                                                 MainProcessEnum::SPACE_DESIGN_STEP_TYPE_SPACE_DESIGN_ASSIGN_WAIT)
                                             ->first();
        //查询任务信息
        $siteInfo = OpenShopSiteMissionModel::query()
                                            ->where("orderNo", $order->orderNo)
                                            ->orderBy("id", "DESC")
                                            ->first();
        $url      = BaseService::getOpenBoardUrl($siteInfo->id) ?? '';

        if (!empty($spaceInfo) && !empty($siteInfo)) {
            $noticeUid     = $spaceInfo['designUid'];
            $designUidInfo = RmsUserService::getRmsUserInfoByUserIds($noticeUid);
            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
            $notice->orderId      = $order->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$order->shopCode;
            $notice->shopName     = $merchantName . '的店';
            $notice->operatorName = $operatorName;
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();
            $feishuUserId = $designUidInfo['data'][0]['feishuUserId'];
            if (strlen($feishuUserId)) {
                (new MessageService())->sendCommonJob([
                    'orderNo'          => $order->orderNo,
                    'missionType'      => '审批',
                    'missionName'      => '上传空间设计图',
                    'shopCode'         => $order->shopCode,
                    'shopName'         => $notice->shopName,
                    'dealUsername'     => $spaceInfo["designName"],
                    'missionTimeStart' => $siteInfo->createdAt->toDateString(),
                    'missionTimeEnd'   => date("Y-m-d H:i:s", $siteInfo->toArray()['expiredAt'])
                ], [$feishuUserId], $url);
            }
        }
        return;

    }


    /**
     * 上传设计图 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function uploadDesignMappingData(
        array $noticeUids,
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        if (!count($noticeUids)) {
            return;
        }
        $body         = RmsUserService::getRmsUserInfoByUserIds($noticeUids);
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        $url       = BaseService::getOrderInfoWenAppUrl($order->orderNo, 0) ?? '';
        $spaceInfo = OpenShopSpaceDesignModel::query()
                                             ->where("orderNo", $order->orderNo)
                                             ->where('step', MainProcessEnum::SPACE_DESIGN_STEP_TYPE_DESIGN_UPLOAD_FILE)
                                             ->first();
        if (!empty($spaceInfo)) {
            foreach ($noticeUids as $noticeUid) {
                // 插入通知
                $notice               = new OpenShopEmployeeNotice;
                $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
                $notice->orderId      = $order->id;
                $notice->userId       = $noticeUid;
                $notice->shopCode     = (string)$order->shopCode;
                $notice->shopName     = $merchantName . '的店';
                $notice->operatorName = $operatorName;
                $notice->createdAt    = time();
                $notice->updatedAt    = time();
                $notice->save();

                $feishuUserId = '';
                foreach (($body['data'] ?? []) as $item) {
                    if ($item['id'] == $noticeUid) {
                        $feishuUserId = $item['feishuUserId'];
                    }
                }
                if (strlen($feishuUserId)) {
                    MessageService::uploadDesignMappingData(
                        $feishuUserId,
                        $order->orderNo,
                        $order->shopCode,
                        $operatorName,
                        $spaceInfo->toArray()['updatedAt'],
                        $url
                    );
                }
            }
        }
        return;

    }


    /**
     * 筹备部确认施工进场 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function engineeringStart(
        array $noticeUids,
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        if (!count($noticeUids)) {
            return;
        }
        $body         = RmsUserService::getRmsUserInfoByUserIds($noticeUids);
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        $siteId = OpenShopSiteMissionModel::getLastFinishSiteId($order->orderNo, MissionTemplateEnum::STEP_STATUS_9);
        $url    = BaseService::getOpenBoardUrl($siteId);

        $info = OpenShopEngineeringConstructionModel::query()
                                                    ->where('orderNo', $order->orderNo)
                                                    ->where('step', MainProcessEnum::ENGINEER_CONSTRUCT_START)
                                                    ->first();
        if (!empty($info)) {
            foreach ($noticeUids as $noticeUid) {
                // 插入通知
                $notice               = new OpenShopEmployeeNotice;
                $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
                $notice->orderId      = $order->id;
                $notice->userId       = $noticeUid;
                $notice->shopCode     = (string)$order->shopCode;
                $notice->shopName     = $merchantName . '的店';
                $notice->operatorName = $operatorName;
                $notice->createdAt    = time();
                $notice->updatedAt    = time();
                $notice->save();

                $feishuUserId = '';
                foreach (($body['data'] ?? []) as $item) {
                    if ($item['id'] == $noticeUid) {
                        $feishuUserId = $item['feishuUserId'];
                    }
                }
                if (strlen($feishuUserId)) {
                    MessageService::engineeringStart(
                        $feishuUserId,
                        $order->orderNo,
                        $order->shopCode,
                        $operatorName,
                        $info->toArray()['updatedAt'],
                        $url
                    );
                }
            }
        }
        return;

    }

    /**
     * 筹备部确认施工完成 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function engineeringOk(
        array $noticeUids,
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        if (!count($noticeUids)) {
            return;
        }
        $body         = RmsUserService::getRmsUserInfoByUserIds($noticeUids);
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        $siteId = OpenShopSiteMissionModel::getLastFinishSiteId($order->orderNo, MissionTemplateEnum::STEP_STATUS_10);
        $url    = BaseService::getOpenBoardUrl($siteId);

        $info = OpenShopEngineeringConstructionModel::query()
                                                    ->where('orderNo', $order->orderNo)
                                                    ->where('step', MainProcessEnum::ENGINEER_CONSTRUCT_CONFIRM_FINISH)
                                                    ->first();
        if (!empty($info)) {
            foreach ($noticeUids as $noticeUid) {
                // 插入通知
                $notice               = new OpenShopEmployeeNotice;
                $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
                $notice->orderId      = $order->id;
                $notice->userId       = $noticeUid;
                $notice->shopCode     = (string)$order->shopCode;
                $notice->shopName     = $merchantName . '的店';
                $notice->operatorName = $operatorName;
                $notice->createdAt    = time();
                $notice->updatedAt    = time();
                $notice->save();

                $feishuUserId = '';
                foreach (($body['data'] ?? []) as $item) {
                    if ($item['id'] == $noticeUid) {
                        $feishuUserId = $item['feishuUserId'];
                    }
                }
                if (strlen($feishuUserId)) {
                    MessageService::engineeringOk(
                        $feishuUserId,
                        $order->orderNo,
                        $order->shopCode,
                        $operatorName,
                        $info->toArray()['updatedAt'],
                        $url
                    );
                }
            }
        }
        return;

    }

    /**
     * 指派营运督导 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function acceptAssignManager(
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        $acceptInfo = OpenShopCheckAcceptModel::query()
                                              ->where('orderNo', $order->orderNo)
                                              ->where('step', MainProcessEnum::SHOP_CHECK_ASSIGN_MANAGER)
                                              ->first();
        //查询任务信息
        $siteInfo = OpenShopSiteMissionModel::query()
                                            ->where("orderNo", $order->orderNo)
                                            ->orderBy('id', 'DESC')
                                            ->first();

        if (!empty($acceptInfo) && !empty($siteInfo)) {
            $url = BaseService::getOpenBoardUrl($siteInfo->id) ?? '';

            $noticeUid     = $acceptInfo['managerId'];
            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
            $notice->orderId      = $order->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$order->shopCode;
            $notice->shopName     = $merchantName . '的店';
            $notice->operatorName = $operatorName;
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();
        }
        return;

    }


    /**
     * 指派营运督导参与人员 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function acceptAssignManagerHistory(
        array $noticeUids,
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        if (!count($noticeUids)) {
            return;
        }
        $body         = RmsUserService::getRmsUserInfoByUserIds($noticeUids);
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        $url        = BaseService::getOrderInfoWenAppUrl($order->orderNo, 0) ?? '';
        $acceptInfo = OpenShopCheckAcceptModel::query()
                                              ->where('orderNo', $order->orderNo)
                                              ->where('step', MainProcessEnum::SHOP_CHECK_ASSIGN_MANAGER)
                                              ->first();
        if (!empty($acceptInfo)) {
            foreach ($noticeUids as $noticeUid) {
                // 插入通知
                $notice               = new OpenShopEmployeeNotice;
                $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
                $notice->orderId      = $order->id;
                $notice->userId       = $noticeUid;
                $notice->shopCode     = (string)$order->shopCode;
                $notice->shopName     = $merchantName . '的店';
                $notice->operatorName = $operatorName;
                $notice->createdAt    = time();
                $notice->updatedAt    = time();
                $notice->save();

                $feishuUserId = '';
                foreach (($body['data'] ?? []) as $item) {
                    if ($item['id'] == $noticeUid) {
                        $feishuUserId = $item['feishuUserId'];
                    }
                }
                if (strlen($feishuUserId)) {
                    MessageService::acceptAssignManagerHistory(
                        $feishuUserId,
                        $order->orderNo,
                        $order->shopCode,
                        $operatorName,
                        $acceptInfo->toArray()['updatedAt'],
                        $url
                    );
                }
            }
            return;
        }
    }


    /**
     * 督导验收&提交表单 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function managerConfirmSubmit(
        array $noticeUids,
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        if (!count($noticeUids)) {
            return;
        }
        $body         = RmsUserService::getRmsUserInfoByUserIds($noticeUids);
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        $siteId = OpenShopSiteMissionModel::getLastFinishSiteId($order->orderNo, MissionTemplateEnum::STEP_STATUS_12);
        $url    = BaseService::getOpenBoardUrl($siteId);


        $acceptInfo = OpenShopCheckAcceptModel::query()
                                              ->where('orderNo', $order->orderNo)
                                              ->where('step', MainProcessEnum::SHOP_CHECK_BY_MANAGER)
                                              ->first();
        if (!empty($acceptInfo)) {
            foreach ($noticeUids as $noticeUid) {
                // 插入通知
                $notice               = new OpenShopEmployeeNotice;
                $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
                $notice->orderId      = $order->id;
                $notice->userId       = $noticeUid;
                $notice->shopCode     = (string)$order->shopCode;
                $notice->shopName     = $merchantName . '的店';
                $notice->operatorName = $operatorName;
                $notice->createdAt    = time();
                $notice->updatedAt    = time();
                $notice->save();

                $feishuUserId = '';
                foreach (($body['data'] ?? []) as $item) {
                    if ($item['id'] == $noticeUid) {
                        $feishuUserId = $item['feishuUserId'];
                    }
                }
                if (strlen($feishuUserId)) {
                    MessageService::managerConfirmSubmit(
                        $feishuUserId,
                        $order->orderNo,
                        $order->shopCode,
                        $operatorName,
                        $acceptInfo->toArray()['updatedAt'],
                        $url
                    );
                }
            }
            return;
        }
    }

    /**
     * 指派开发经理任务 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function assignManagerJob(
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        $managerInfo = OpenShopLocationModel::query()
                                            ->where("orderNo", $order->orderNo)
                                            ->where('step', MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER)
                                            ->first();

        //查询任务信息
        $siteInfo = OpenShopSiteMissionModel::query()
                                            ->where("orderNo", $order->orderNo)
                                            ->orderBy('id', 'DESC')
                                            ->first();
        if (!empty($managerInfo) && !empty($siteInfo)) {
            $url = BaseService::getSiteAppletUrl($order->orderNo) ?? '';

            $shopName = (new RmsShopApi())->getShopByCode($order->shopCode)['data']['name'] ?? '';

            $noticeUid     = $managerInfo['investmentManagerId'];
            $designUidInfo = RmsUserService::getRmsUserInfoByUserIds($noticeUid);
            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
            $notice->orderId      = $order->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$order->shopCode;
            $notice->shopName     = $shopName;
            $notice->operatorName = $operatorName;
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();
            $feishuUserId = $designUidInfo['data'][0]['feishuUserId'];
            if (strlen($feishuUserId)) {
                MessageService::assignManagerJob(
                    $feishuUserId,
                    $order->orderNo,
                    $order->shopCode,
                    $designUidInfo['data'][0]['username'],
                    $url,
                    $notice->shopName,
                    $siteInfo->createdAt->toDateString(),
                    date("Y-m-d H:i:s", $siteInfo->toArray()['expiredAt'])
                );
            }
        }
    }


    /**
     * 选址报告上传参与人员 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function locationUploadedHistory(
        array $noticeUids,
        OpenShopSignOrderModel $order
    ) {
        if (!count($noticeUids)) {
            return;
        }
        $body         = RmsUserService::getRmsUserInfoByUserIds($noticeUids);
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        $url         = BaseService::getOrderInfoWenAppUrl($order->orderNo, 0) ?? '';
        $managerInfo = OpenShopLocationModel::query()
                                            ->where("orderNo", $order->orderNo)
                                            ->where('step', MainProcessEnum::SHOP_LOCATION_FORM_SUBMIT)
                                            ->first();

        $body2        = RmsUserService::getRmsUserInfoByUserIds([$managerInfo->investmentManagerId]);
        $operatorName = $body2['data'][0]['username'] ?? '';

        if (!empty($managerInfo)) {
            foreach ($noticeUids as $noticeUid) {
                // 插入通知
                $notice               = new OpenShopEmployeeNotice;
                $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
                $notice->orderId      = $order->id;
                $notice->userId       = $noticeUid;
                $notice->shopCode     = (string)$order->shopCode;
                $notice->shopName     = $merchantName . '的店';
                $notice->operatorName = $operatorName;
                $notice->createdAt    = time();
                $notice->updatedAt    = time();
                $notice->save();

                $feishuUserId = '';
                foreach (($body['data'] ?? []) as $item) {
                    if ($item['id'] == $noticeUid) {
                        $feishuUserId = $item['feishuUserId'];
                    }
                }
                if (strlen($feishuUserId)) {
                    MessageService::locationUploadedHistory(
                        $feishuUserId,
                        $order->orderNo,
                        $order->shopCode,
                        $operatorName,
                        $managerInfo->updatedAt->toDateString(),
                        $url
                    );
                }
            }
        }
    }


    /**
     * 门店已经确认选址 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function locationConfirmed(
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        Log::info("门店已经确认选址飞书消息入口：" . $order->orderNo);
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        //查询任务信息
        $siteInfo = OpenShopSiteMissionModel::query()
                                            ->where("orderNo", $order->orderNo)
                                            ->orderBy('id', 'DESC')
                                            ->first();
        if (!empty($siteInfo)) {
            $url = BaseService::getOpenBoardUrl($siteInfo->id) ?? '';

            $noticeUid     = $siteInfo['dealUid'];
            $designUidInfo = RmsUserService::getRmsUserInfoByUserIds($noticeUid);
            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
            $notice->orderId      = $order->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$order->shopCode;
            $notice->shopName     = $merchantName . '的店';
            $notice->operatorName = $operatorName;
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();
            $feishuUserId = $designUidInfo['data'][0]['feishuUserId'];
            Log::info("门店已经确认选址飞书消息进入：" . $order->orderNo . '---' . $feishuUserId . '-----' . $siteInfo['id']);
            if (strlen($feishuUserId)) {
                MessageService::locationConfirmed(
                    $feishuUserId,
                    $order->orderNo,
                    $order->shopCode,
                    $operatorName,
                    $url,
                    $notice->shopName,
                    $siteInfo->createdAt->toDateString(),
                    date("Y-m-d H:i:s", $siteInfo->toArray()['expiredAt'])
                );
            }
        }
        Log::info("门店已经确认选址飞书消息数据为空：" . $order->orderNo);
        return;

    }


    /**
     * 门店已经确认选址 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public
    static function locationConfirmedHistory(
        array $noticeUids,
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        if (!count($noticeUids)) {
            return;
        }
        $body         = RmsUserService::getRmsUserInfoByUserIds($noticeUids);
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        $url         = BaseService::getOrderInfoWenAppUrl($order->orderNo, 0) ?? '';
        $managerInfo = OpenShopLocationModel::query()
                                            ->where("orderNo", $order->orderNo)
                                            ->where('step', MainProcessEnum::SHOP_LOCATION_CONFIRM)
                                            ->first();
        if (!empty($managerInfo)) {
            foreach ($noticeUids as $noticeUid) {
                // 插入通知
                $notice               = new OpenShopEmployeeNotice;
                $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
                $notice->orderId      = $order->id;
                $notice->userId       = $noticeUid;
                $notice->shopCode     = (string)$order->shopCode;
                $notice->shopName     = $merchantName . '的店';
                $notice->operatorName = $operatorName;
                $notice->createdAt    = time();
                $notice->updatedAt    = time();
                $notice->save();
                $feishuUserId = '';
                foreach (($body['data'] ?? []) as $item) {
                    if ($item['id'] == $noticeUid) {
                        $feishuUserId = $item['feishuUserId'];
                    }
                }
                if (strlen($feishuUserId)) {
                    MessageService::locationConfirmedHistory(
                        $feishuUserId,
                        $order->orderNo,
                        $order->shopCode,
                        $merchantName,
                        $managerInfo->updatedAt->toDateString(),
                        $url
                    );
                }
            }
            return;
        }
    }


    /**
     * 筹备部确认施工进场 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function engineeringStartJob(
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        //查询任务信息
        $siteInfo = OpenShopSiteMissionModel::query()
                                            ->where("orderNo", $order->orderNo)
                                            ->where('stepStatus', MissionTemplateEnum::STEP_STATUS_10)
                                            ->orderByDesc('id')
                                            ->first();

        Log::info('engineeringStartJobbbbbb', $siteInfo->toArray());

        if (!empty($siteInfo)) {
            $url = BaseService::getOpenBoardUrl($siteInfo->id) ?? '';

            $noticeUid     = $siteInfo['dealUid'];
            $designUidInfo = RmsUserService::getRmsUserInfoByUserIds($noticeUid);
            $operatorName  = $designUidInfo['data'][0]['username'];
            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
            $notice->orderId      = $order->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$order->shopCode;
            $notice->shopName     = $merchantName . '的店';
            $notice->operatorName = $operatorName;
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();
            $feishuUserId = $designUidInfo['data'][0]['feishuUserId'];
            if (strlen($feishuUserId)) {
                MessageService::engineeringStartJob(
                    $feishuUserId,
                    $order->orderNo,
                    $order->shopCode,
                    $operatorName,
                    $url,
                    $notice->shopName,
                    $siteInfo->createdAt->toDateString(),
                    date("Y-m-d H:i:s", $siteInfo->toArray()['expiredAt'])
                );
            }
        }
        return;

    }


    /**
     * 筹备部确认施工完成 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function engineeringOkJob(
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        //查询任务信息
        $siteInfo = OpenShopSiteMissionModel::query()
                                            ->where("orderNo", $order->orderNo)
                                            ->orderBy('id', 'DESC')
                                            ->first();
        if (!empty($siteInfo)) {
            $url = BaseService::getOpenBoardUrl($siteInfo->id) ?? '';

            $noticeUid     = $siteInfo['dealUid'];
            $designUidInfo = RmsUserService::getRmsUserInfoByUserIds($noticeUid);
            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
            $notice->orderId      = $order->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$order->shopCode;
            $notice->shopName     = $merchantName . '的店';
            $notice->operatorName = $operatorName;
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();
            $feishuUserId = $designUidInfo['data'][0]['feishuUserId'];
            if (strlen($feishuUserId)) {
                MessageService::engineeringOkJob(
                    $feishuUserId,
                    $order->orderNo,
                    $order->shopCode,
                    $designUidInfo['data'][0]['username'],
                    $url,
                    $notice->shopName,
                    $siteInfo->createdAt->toDateString(),
                    date("Y-m-d H:i:s", $siteInfo->toArray()['expiredAt'])
                );
            }
        }
        return;

    }


    /**
     * 督导验收 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function managerConfirmSubmitJob(
        OpenShopSignOrderModel $order,
        string $operatorName
    ) {
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        //查询任务信息
        $siteInfo = OpenShopSiteMissionModel::query()
                                            ->where("orderNo", $order->orderNo)
                                            ->orderBy('id', 'DESC')
                                            ->first();
        if (!empty($siteInfo)) {
            $url           = BaseService::getOpenBoardUrl($siteInfo->id) ?? '';
            $noticeUid     = $siteInfo['dealUid'];
            $designUidInfo = RmsUserService::getRmsUserInfoByUserIds($noticeUid);
            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
            $notice->orderId      = $order->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$order->shopCode;
            $notice->shopName     = $merchantName . '的店';
            $notice->operatorName = $operatorName;
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();
            $feishuUserId = $designUidInfo['data'][0]['feishuUserId'];
            if (strlen($feishuUserId)) {
                MessageService::managerConfirmSubmitJob(
                    $feishuUserId,
                    $order->orderNo,
                    $order->shopCode,
                    $operatorName,
                    $url,
                    $notice->shopName,
                    $siteInfo->createdAt->toDateString(),
                    date("Y-m-d H:i:s", $siteInfo->toArray()['expiredAt'])
                );
            }
        }
        return;
    }


    /**
     * 签合同任务 飞书消息
     * @param array $noticeUids
     * @param OpenShopSignOrderModel $order
     * @param string $operatorName
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function signedJob(OpenShopSignOrderModel $order, string $operatorName = '')
    {
        $merchantName = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($order->orderNo))->name;

        //查询任务信息
        $siteInfo = OpenShopSiteMissionModel::query()
                                            ->where("orderNo", $order->orderNo)
                                            ->orderBy('id', 'DESC')
                                            ->first();
        //获取
        if (!empty($siteInfo)) {
            $url = BaseService::getOpenBoardUrl($siteInfo->id) ?? '';

            $noticeUid     = $siteInfo['dealUid'];
            $designUidInfo = RmsUserService::getRmsUserInfoByUserIds($noticeUid);
            // 插入通知
            $notice               = new OpenShopEmployeeNotice;
            $notice->content      = MainProcessEnum::SHOP_LOCATION_MAP[MainProcessEnum::SHOP_LOCATION_ASSIGN_MANAGER];
            $notice->orderId      = $order->id;
            $notice->userId       = $noticeUid;
            $notice->shopCode     = (string)$order->shopCode;
            $notice->shopName     = $merchantName . '的店';
            $notice->operatorName = $operatorName;
            $notice->createdAt    = time();
            $notice->updatedAt    = time();
            $notice->save();
            $feishuUserId = $designUidInfo['data'][0]['feishuUserId'];

            if (strlen($feishuUserId)) {
                MessageService::signedJob(
                    $feishuUserId,
                    $order->orderNo,
                    $order->shopCode,
                    $operatorName,
                    $url,
                    $notice->shopName,
                    $siteInfo->createdAt->toDateString(),
                    date("Y-m-d H:i:s", $siteInfo->toArray()['expiredAt'])
                );
            }
        }
        return;

    }

    /**
     * 获取店铺code
     *
     * @return \Illuminate\Database\Eloquent\HigherOrderBuilderProxy|mixed
     */
    public function getShopCode()
    {
        return $this->orderInfo->shopCode;
    }

    /**
     * 订单数据信息
     *
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getOrderInfo(): object
    {
        // 只查基本信息需要什么通过懒加载获取, 或者另写方法
        return OpenShopSignOrderModel::query()
                                     ->where('orderNo', $this->orderNo)
                                     ->first();
    }

    /**
     * 获取店名
     *
     * @return string
     */
    public function getShopName(): string
    {
        if (empty($this->orderInfo->shopCode)) {
            $merchantUser = (string)optional(OpenShopUserIdentityCardModel::getDataByOrderNo($this->orderNo))->name;
            $shopName     = $merchantUser . '的店';
        } else {
            $shopName = ShopService::getShopNameByCode($this->orderInfo->shopCode); // 门店名称
        }

        return $shopName;
    }

    /**
     * 获取订单号
     *
     * @return string
     */
    public function getOrderNo()
    {
        return $this->orderNo;
    }

    /**
     * set 任务标题.
     *
     * @param string $missionContent
     */
    public function setMissionContent(string $missionContent)
    {
        $this->missionContent = $missionContent;
    }

    /**
     * 任务名称
     *
     * @return string
     */
    public function getMissionContent()
    {
        return $this->missionContent;
    }

    /**
     * 任务类型
     *
     * @return string
     */
    public function getMissionType()
    {
        return $this->missionType;
    }

    /**
     * 设置 url
     *
     * @param int $missionId
     */
    public function setUrl($missionId = 0)
    {
        $this->url = BaseService::getOrderInfoWenAppUrl($this->orderNo, $missionId);
    }

    /*
     * 设置选址 app 的 url
     */
    public function setSiteUrl()
    {
        $this->url = BaseService::getSiteAppletUrl($this->getOrderNo());
    }

    /**
     * 设置开店 小程序的跳板url
     * @param int $missionId
     * @return void
     */
    public function setOpenBoardUrl(int $missionId)
    {
        $this->url = BaseService::getOpenBoardUrl($missionId);
    }

    public function getUrl()
    {
        return $this->url;
    }

    /**
     * 设置推送人
     *
     * @param $userIds
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function setPushUserInfos(array $userIds)
    {
        if (empty($userIds)) {
            return;
        }
        $body               = RmsUserService::getRmsUserInfoByUserIds($userIds);
        $data               = $body['data'];
        $this->pushUserInfo = $data;
    }

    /**
     * 获取用户信息
     *
     * @return array
     */
    public function getPushUserInfo()
    {
        return $this->pushUserInfo;
    }

    public function getPushUserFeiShuId(): array
    {
        return array_column($this->getPushUserInfo(), 'feishuUserId');
    }

    /**
     * set
     *
     * @param int $userId
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function setMissionDealUserInfo(int $userId)
    {
        Log::info("dealUserInfo-userId", ['userId' => $userId]);
        $result = RmsUserService::getRmsUserInfoByUserIds([$userId]);
        Log::info("dealUserInfo", ['userInfo' => $result]);
        $this->missionDealUserInfo = $result['data'][0];
    }

    /**
     * get
     *
     * @return array
     */
    public function getMissionDealUserInfo()
    {
        return $this->missionDealUserInfo;
    }

}
